package com.hpe.aruba.CPPM.utils;


import android.util.Log;

import com.android.volley.RequestQueue;
import com.hpe.aruba.CPPM.interfaces.StringInterface;
import com.hpe.aruba.CPPM.objects.Device;

import java.util.HashMap;

public class MacAdressUtils {

    final static String TAG = "CLEARPASS";

    public static void getVendorAsync(RequestQueue queue, Device mac, StringInterface onSuccess, StringInterface onError) {
        String url = "https://api.macvendors.com/" + mac.getMac();
        WebUtils.get(queue, url, new HashMap<>(), response -> {
            if (response.startsWith("{")) {
                onError.apply(response);
                return;
            }
            onSuccess.apply(response);
        }, onError);
    }

    public static String normalizeMac(String mac) {
        /*check if length is */
        /*magic numbers*/
        final byte MAC_LENGTH_WITH_SEPARATORS = 17;
        final byte MAC_LENGTH_WITHOUT_SEPARATORS = 12;

        /*to uppercase in every case*/
        mac = mac.toUpperCase();

        if (mac.length() == MAC_LENGTH_WITH_SEPARATORS) {
            /*if it becomes necessary add separator checking here (-,:, etc?)*/
            return mac;
        } else if (mac.length() == MAC_LENGTH_WITHOUT_SEPARATORS) {
            StringBuilder macBuilder = new StringBuilder(mac);
            /*hardcoded for readability, macs are the same length*/
            final byte[] insertAt = {2,5,8,11,14};
            for (byte at : insertAt) {
                macBuilder.insert(at, "-");
            }
            mac = macBuilder.toString();
            return mac;
        } else {
            Log.e(TAG, "Malformed MAC: " + mac);
            return mac;
        }
    }

    /*forms MAC to all lowercase without '-' for eg clearpass insight*/
    public static String baseMac(String mac) {
        mac = mac.toLowerCase();
        StringBuilder newMac = new StringBuilder();
        for (char x : mac.toCharArray()) {
            if (x != '-' && x != ':') newMac.append(x);
        }
        return newMac.toString();
    }
}
